let t = 0;
let timer;
const root = document.querySelector('#root');
const span = document.querySelectorAll('span');
const projectItem = document.querySelectorAll('.project div');
const rootBg = document.querySelector('#root-bg');
const boxSearchContainer = document.querySelector('.box_search');
// 输入搜索框
const searchInput = boxSearchContainer.querySelector('textarea');

const methods = {
  /** 时间定时 */
  time () {
    clearTimeout(t); //清除定时器
    const dt = new Date();
    let h = dt.getHours(); //获取时
    let m = dt.getMinutes(); //获取分
    if (m < 10) m = '0' + m;
    document.getElementById('showTime').innerHTML = h + ':' + m;
    t = setTimeout(methods.time, 1000);
    if (m % 2 === 0) {
      rootBg.style.backgroundImage = 'url(./bg.webp)'
      span.forEach(item => item.style.color = '#399953')
      projectItem.forEach(item => item.style.backgroundColor = 'rgba(255, 255, 255, 0.5)')  
    } else {
      rootBg.style.backgroundImage = 'url(./bg.jpg)'
      span.forEach(item => item.style.color = '#fff')
      projectItem.forEach(item => item.style.backgroundColor = 'rgba(0, 0, 0, 0.5)')  
    }
  },
  /** 监听键盘事件 */
  keydown (e) {
    e = e || window.e;
    if (e.keyCode == 13) {
      methods.search()
    }
  },
  /** 输入框搜索 */
  search () {
    methods.wordToSpeak();
  },
  wordToSpeak() {
    const speech = window.speechSynthesis; 
    speech.cancel();
    const value = searchInput.value;
    if (!value) return;
    speech.onvoiceschanged = () => {
      const utterance = new SpeechSynthesisUtterance(value);
      const voiceList = speech.getVoices()
      const beChoose = 'Microsoft Yaoyao - Chinese (Simplified, PRC)';
      const chooseVoice = voiceList.find(item => item.name.trim() === beChoose.trim());
      utterance.voice = chooseVoice;
      utterance.rate = 0.7;
      speech.speak(utterance);
    }
  }
}

// 时间定时实例化
methods.time();

searchInput.addEventListener('keydown', methods.keydown);
boxSearchContainer.addEventListener('click', methods.focus);
searchInput.addEventListener('input', () => {
  // 清除之前的定时器
  clearTimeout(timer);
  // 设置新的定时器
  timer = setTimeout(() => {
    methods.wordToSpeak();
  }, 1000); // 1秒后触发
});
